<template>
  <section>
    <section class="topic-num">
      <!-- <section
        :class="{ check: topicNum === i - 1 }"
        v-for="i in list.length"
        :key="i"
        @click="topicChange(i - 1)"
      >
        {{ i }}
      </section> -->
      <section>{{ topicNum + 1 }}/{{ list.length }}</section>
    </section>
    <section class="list">
      <section
        v-for="(item, i) in list"
        :key="i"
        class="list-item"
        :style="{
          left: i * 100 - topicNum * 100 + 'vw',
          opacity: i == topicNum ? 1 : 0,
        }"
      >
        <section class="list-topic">
          {{ i + 1 }}<span>、</span
          >{{ item.type === 'checkbox' ? '(多选题)' : '' }}{{ item.topic }}
        </section>
        <section
          v-for="option in item.options"
          :key="option"
          class="checkbox"
          :class="{
            success: isShowAnswer[topicNum] && option.includes('correct'),
            error:
              !option.includes('correct') &&
              isShowAnswer[topicNum] &&
              checkList[i].includes(option) &&
              !getAnswerType(item),
          }"
          @click="checkChange(item, option)"
        >
          <span :class="{ check: checkList[i].includes(option) }"></span
          >{{ option.replace('correct', '') }}
        </section>
        <section
          v-if="isShowAnswer[i]"
          class="analysis"
          style=""
          v-html="formatAnswer(item.answer)"
        />
      </section>
    </section>
    <section>
      <el-button @click="topicChange('pre')">上一题</el-button>
      <el-button @click="topicChange('next')">下一题</el-button>
      <el-button @click="showAnswer">解析</el-button>
    </section>
  </section>
</template>

<script lang="ts" setup>
import { reactive, ref, defineProps, computed, ComputedRef } from 'vue';
import { cloneDeep, localStorage } from '@/utils/metheds';
import optionList from '@/views/Temp/data/subjectOption';
import { replaceText } from '@/views/Temp/metheds';
import { CheckItem, SubjectItem, Subject } from './interfaceType';
const props = defineProps({
  subjectList: Array,
});
const subjectList:
  | ComputedRef<Array<SubjectItem>>
  | ComputedRef<Array<CheckItem>>
  | ComputedRef<Array<any>> = computed(() => {
  return props?.subjectList ?? optionList;
});
const currentSubjectKey = ref('现代管理学');
// 题目标号
const topicNum = ref(0);
// 所有选择的答案集合
const checkList: Array<Array<string>> = reactive([]);
// 所有答案的显示状态
const isShowAnswer: Array<number> = reactive([]);
const cloneList: Array<SubjectItem> | Array<CheckItem> = subjectList.value
  .length
  ? subjectList.value
  : optionList;
// 题目列表
const list: Array<CheckItem> = reactive(
  cloneDeep(
    cloneList.filter(
      (item: SubjectItem | CheckItem) => item.topic && item.options.length,
    ),
  ),
);
for (let i = 0; i < list.length; i++) {
  checkList[i] = [''];
  // 随机打乱题目顺序
  const random = Math.floor(Math.random() * (list.length - 1 - i)) + i;
  const temp = cloneDeep(list[i]);
  list.splice(i, 1, list[random]);
  list.splice(random, 1, temp);
  // if (!list[i].options.some((item) => item.includes('correct')))
  //   console.log(list[i]);
  // 随机打乱题目选项顺序
  for (let j = 0; j < list[i].options.length; j++) {
    const random = Math.floor(Math.random() * (list[i].options.length - 1 - 0));
    const temp = cloneDeep(list[i].options[j]);
    list[i].options[j] = list[i].options[random];
    list[i].options[random] = temp;
  }
}
// 题目切换
function topicChange(type: string | number) {
  if (type === 'pre') {
    topicNum.value > 0 && topicNum.value--;
  } else if (type === 'next') {
    topicNum.value < list.length - 1 && topicNum.value++;
  } else if (typeof type === 'number') {
    topicNum.value = type;
  }
}
// 选择选项
function checkChange(item: CheckItem, option: string) {
  if (isShowAnswer[topicNum.value] === 1) return;
  switch (item.type) {
    case 'radio':
      checkList[topicNum.value] = [option];
      break;
    case 'checkbox':
      {
        if (checkList[topicNum.value][0] === '')
          checkList[topicNum.value].splice(0, 1);
        const index = checkList[topicNum.value].indexOf(option);
        index === -1
          ? checkList[topicNum.value].push(option)
          : checkList[topicNum.value].splice(index, 1);
      }
      break;
    default:
      break;
  }
}
// 显示答案
function showAnswer() {
  isShowAnswer[topicNum.value] = 1;
  const type: string = list[topicNum.value].type;
  const answer: Array<string> = checkList[topicNum.value];
  let success = true;
  switch (type) {
    case 'radio':
      success = !!answer[0].includes('correct');
      break;
    case 'checkbox':
      for (let i = 0; i < answer.length; i++) {
        success = !!answer[i].includes('correct');
        if (!success) break;
      }
      break;
    default:
      break;
  }
  const historyList = localStorage('subjects', 'getItem') ?? [];
  console.log(historyList, 'historyList');
  const currentSubjectIndex = historyList?.findIndex(
    (item: Subject) => item.key === currentSubjectKey.value,
  );
  const defaultSubject = {
    key: currentSubjectKey.value,
    list: [],
  };
  const currentSubject =
    currentSubjectIndex === -1
      ? defaultSubject
      : historyList[currentSubjectIndex];
  const index = currentSubject.list.findIndex(
    (item: SubjectItem) => item.topic === list[topicNum.value].topic,
  );
  switch (index) {
    case -1:
      currentSubject.list.push({
        ...list[topicNum.value],
        count: 1,
        errorCount: success ? 0 : 1,
      });
      break;
    default:
      currentSubject.list[index].count++;
      success ?? currentSubject.list[index].errorCount++;
      break;
  }
  currentSubjectIndex === -1
    ? historyList.push(currentSubject)
    : historyList.splice(currentSubjectIndex, 1, currentSubject);
  localStorage('subjects', 'setItem', historyList);
}
// 获取答案类型 正确、错误 以增加class类名 添加样式
function getAnswerType(item: CheckItem) {
  if (!isShowAnswer[topicNum.value]) return false;
  let result = false;
  switch (item.type) {
    case 'radio':
      result = checkList[topicNum.value][0].includes('correct');
      break;
    case 'checkbox':
      break;
    default:
      break;
  }
  return result;
}
// 格式化文字 (在。|；|：后面增加换行)
function formatAnswer(str: string): string {
  let res = replaceText(str, '。');
  res = replaceText(res, '；');
  res = replaceText(res, '：');
  return res;
}
</script>

<style lang="scss">
.list {
  position: relative;
  height: 500px;
  overflow: hidden;
  text-align-last: left;

  &-item {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    transition: opacity 2s;
  }

  &-topic {
    font-weight: 900;
    font-size: 24px;
    margin: 16px 0;
  }
}

.checkbox {
  display: flex;
  align-items: center;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-bottom: 8px;
  font-size: 18px;
  cursor: pointer;

  &.success {
    color: #67c23a;
    font-weight: 700;
  }

  &.error {
    color: #f56c6c;
  }

  span {
    display: inline-block;
    width: 16px;
    height: 16px;
    margin-right: 8px;
    border: 1px solid #1f1515;

    &.check {
      background-color: #35aafc;
    }
  }
}

.topic-num {
  display: flex;
  flex-wrap: wrap;
  // > section {
  //   display: flex;
  //   justify-content: center;
  //   align-items: center;
  //   width: 30px;
  //   height: 30px;
  //   border: 1px solid #ccc;
  //   border-radius: 3px;
  //   margin-right: 8px;
  //   margin-bottom: 8px;
  //   cursor: pointer;
  //   &.check {
  //     background-color: #35aafc;
  //     color: #fff;
  //   }
  // }
}

.analysis {
  margin: 0 auto;
  text-align: left;
  text-indent: 2em;
  overflow-y: scroll;
  height: 200px;
}
</style>
